#!/usr/bin/env python
# coding: utf-8

# Setp one:
# note: Reload django settings
import logging
import json
import os
import sys
import time

import django

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
os.chdir(os.path.join(BASE_DIR, "yijiao_main"))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
sys.path.insert(0, os.path.join(BASE_DIR, "pylib"))
sys.path.insert(0, os.path.join(BASE_DIR, "yijiao_main"))
django.setup()

# Setp two:
# note: Load function with logging, django model
from services.datamodel.schoolclass.models import mm_Class
from services.datamodel.student.models import mm_Student

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
    filename=os.path.join("/tmp", "register_many_studnet.log")
)


# Setp three:
# note: Running
def register_many_studnet():
    with open(os.path.join(BASE_DIR, "yijiao_main", "services\\script_offline\\register_information.txt"), "r") as f:
        invitecode, create_number = f.readlines()[:2]
        invitecode = invitecode.replace("\n", "")
        create_number = create_number.replace("\n", "")
        status = True
        if not create_number.isdigit():
            status =False

    class_instance = mm_Class.get_or_default(invitecode=int(invitecode))
    if not class_instance or not status:
        print("班级邀请码或者创建人数数据有误")
        return
    class_id = class_instance.id

    if mm_Student.getStudentNumberInClass(class_id) + int(create_number) >= class_instance.studentlimit:
        print("创建的学生数量将会超过班级上限，已经取消")
        return

    schoolid = class_instance.school_id
    gradeid = class_instance.grade_id

    for i in range(1, int(create_number) + 1):
        i = "{}".format(i + 100000)[-4:]
        i = "{}{}".format(invitecode, i)[-8:]
        mm_Student.addStudent(i, i, schoolid, gradeid, class_id, i)
        print(i)


if __name__ == "__main__":
    start_time = time.time()
    register_many_studnet()
    logging.info("end")
    print(time.time() - start_time)
